package com.etime.shycourse.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.etime.shycourse.config.Tools;
import com.etime.shycourse.dao.OrgTeacherMapper;
import com.etime.shycourse.dao.OrganizationMapper;
import com.etime.shycourse.dao.SysUserMapper;
import com.etime.shycourse.dto.OrgTeacherDtoS;
import com.etime.shycourse.dto.UserTeacherDto;
import com.etime.shycourse.pojo.SysUser;
import com.etime.shycourse.pojo.Teacher;
import com.etime.shycourse.services.interfaces.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.DigestUtils;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wb
 * @since 2021-12-14
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private OrgTeacherMapper tMapper;
    @Autowired
    private SysUserMapper uMapper;
    @Autowired
    private OrganizationMapper oMapper;
    @Autowired
    private Tools tools;

    /**
     * 修改机构教师 第一步
     * <p></p>
     *
     * @return dto
     * 第一步 查询 通过列表中点击携带id 修改进入修改页面。
     * 查询出的参数有
     * sysuser表 用户名 姓名* 专业* 联展电话.* Emal
     * <p>
     * teacher表 教师Tith * 技术标名 * 简介
     */
    @Override
    public OrgTeacherDtoS selectOrgUserTeacherById(Integer tecId) {
        // 根据用户id的进行查询
        return uMapper.selectUserTeacherById(tecId, null);
    }

    /**
     * 修改机构教师 第二步
     *
     * @param dto 用户实体 用户id 教师id
     * @return 0失败；1成功
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateOrgUserTeacher(OrgTeacherDtoS dto) {
        if (dto.getTecid() != null & dto.getUserid() != null) {
            int teacherUpdate = 0;
            // 根据教师id 修改教师时的返回值
            SysUser sysUser = new SysUser();
            // 根据 用户id 修改sysUser表
            sysUser.setUserid(dto.getUserid());
            // 姓名
            if (dto.getUsertruename() != null) {
                sysUser.setUsertruename(dto.getUsertruename());
            }
            // 用户名
            if (dto.getUsername() != null) {
                sysUser.setUsername(dto.getUsername());
            }
            if (dto.getUsermajor() != null) {
                sysUser.setUsermajor(dto.getUsermajor());
            }
            if (dto.getUserphone() != null) {
                sysUser.setUserphone(dto.getUserphone());
            }
            if (dto.getUseremail() != null) {
                sysUser.setUseremail(dto.getUseremail());
            }
            if (dto.getShowpic() != null) {
                sysUser.setShowpic(dto.getShowpic());
            }
            //使用两次MD5加密
            if (dto.getUserpwd() != null) {
                String userPwd = dto.getUserpwd();
                // 查询到数据库的密码
                SysUser user2 = uMapper.selectById(dto.getUserid());
                // 判断是否一致 相等为 true ； 如果前端传来的值与数据库的一致，就不进行加密；反之不加密
                if (!userPwd.equals(user2.getUserpwd())) {
                    // 新密码
                    sysUser.setUserpwd(DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(dto.getUserpwd().getBytes()).getBytes()));
                }
            }
            //根据 教师id 修改teacher表
            Teacher teacher = new Teacher();
            teacher.setTecid(dto.getTecid());
            if (dto.getTecdesc() != null) {
                teacher.setTecdesc(dto.getTecdesc());
            }
            if (dto.getTectitle() != null) {
                teacher.setTectitle(dto.getTectitle());
            }
            if (dto.getTeclabel() != null) {
                teacher.setTeclabel(dto.getTeclabel());
            }
            // 先执行查询操作  如果查询出来的数据跟修改前一致就 不进行修改
            try {
                // 1 先修改 user表
                int userUpdate = uMapper.updateById(sysUser);
                // userUpdate 根据用户id 修改用户时的返回值
                if (userUpdate == 0) {
                    throw new Exception("添加用户信息失败！");
                }
                // 2 再修改 Teacher表
                teacherUpdate = tMapper.updateById(teacher);
                if (teacherUpdate == 0) {
                    throw new Exception("添加教师信息失败！");  // teacherUpdate 根据教师id 修改教师时的返回值
                }
            } catch (Exception e) {
                e.printStackTrace();
                // @Transactional和try catch捕获异常会让注解失效
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            return teacherUpdate;
        }
        return 0;
    }

    /**
     * 根据用户id查询用户详细信息
     *
     * @param userid
     * @return
     */
    @Override
    public SysUser selectSysUserById(Integer userid) {
        return uMapper.selectById(userid);
    }

    /**
     * 通过用户id 查询出用户信息
     * <p></p>
     *
     * @param userId
     * @return OrgTeacherDtoS
     */
    @Override
    public OrgTeacherDtoS selectOrgUserById(Integer userId) {
        return uMapper.selectUserTeacherById(null, userId);
    }

    /**
     * 1 修改用户所属机构     2022-02-26 17:30:34 wb
     * 2 创建教师信息
     *
     * @param userTeacherDto 用户 教师实体
     * @return 0失败；1成功
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int upUserCreateTeacher(UserTeacherDto userTeacherDto) {
        int userUpdate = 0;
        if (userTeacherDto == null) {
            return 0;
        }
        try {

            // 1 先修改 user表 是否是教师
            SysUser sysUser = new SysUser();
            // 根据 用户id 修改sysUser表
            sysUser.setUserid(userTeacherDto.getUserid());
            // 用户名
            if (userTeacherDto.getUsername() != null) {
                sysUser.setUsername(userTeacherDto.getUsername());
            }

            //改用户的所属机构
            if (userTeacherDto.getIsteacher() != null) {
                sysUser.setIsteacher(userTeacherDto.getIsteacher());
            }
            //使用两次MD5加密
            if (userTeacherDto.getUserpwd() != null) {
                String userPwd = userTeacherDto.getUserpwd();
                // 查询到数据库的密码
                SysUser user2 = uMapper.selectById(userTeacherDto.getUserid());
                // 判断是否一致 相等为 true ； 如果前端传来的值与数据库的一致，就不进行加密；反之不加密
                if (!userPwd.equals(user2.getUserpwd())) {
                    // 新密码
                    sysUser.setUserpwd(DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(userTeacherDto.getUserpwd().getBytes()).getBytes()));
                }
            }
            // 用户名
            if (userTeacherDto.getUsername() != null) {
                sysUser.setUsername(userTeacherDto.getUsername());
            }
            // 用户姓名
            if (userTeacherDto.getUsertruename() != null) {
                sysUser.setUsertruename(userTeacherDto.getUsertruename());
            }
            // 用户职业
            if (userTeacherDto.getUseroccupation() != null) {
                sysUser.setUseroccupation(userTeacherDto.getUseroccupation());
            }
            // 专业
            if (userTeacherDto.getUsermajor() != null) {
                sysUser.setUsermajor(userTeacherDto.getUsermajor());
            }
            // 易启学账户id
            if (userTeacherDto.getEdusohoid() != null) {
                sysUser.setEdusohoid(userTeacherDto.getEdusohoid());
            }
            if (userTeacherDto.getUserphone() != null) {
                sysUser.setUserphone(userTeacherDto.getUserphone());
            }
            if (userTeacherDto.getUseremail() != null) {
                sysUser.setUseremail(userTeacherDto.getUseremail());
            }
            // 头像
            if (userTeacherDto.getShowpic() != null) {
                sysUser.setShowpic(userTeacherDto.getShowpic());
            }
            userUpdate = uMapper.updateById(sysUser);
            // userUpdate 根据用户id 修改用户时的返回值
            if (userUpdate == 0) {
                throw new Exception("修改用户信息失败！");
            }
            // 2 添加 Teacher表
            // 默认教师审核通
            userTeacherDto.setTecauditstate(1);
            //审核 1：通过；2：不通过
            int insert = tMapper.insert((Teacher) userTeacherDto);
            if (insert == 0) {
                throw new Exception("添加教师信息失败！");  // teacherUpdate 根据教师id 修改教师时的返回值
            } else {
                //  根据用户id redis缓存删除
                tools.deleteUserFromRedisByUserId(userTeacherDto.getUserid());
                return 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
            // @Transactional和try catch捕获异常会让注解失效
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 0;
        }
    }

    /**
     * 修改教师信息
     *
     * @param userTeacherDto
     * @return 0失败；1成功
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int upDataTeacher(UserTeacherDto userTeacherDto) {
        try {
            // 1 先修改 user表 是否是教师
            SysUser sysUser = new SysUser();
            // 根据 用户id 修改sysUser表
            sysUser.setUserid(userTeacherDto.getUserid());
            //使用两次MD5加密
            if (userTeacherDto.getUserpwd() != null) {
                String userPwd = userTeacherDto.getUserpwd();
                // 查询到数据库的密码
                SysUser user2 = uMapper.selectById(userTeacherDto.getUserid());
                // 判断是否一致 相等为 true ； 如果前端传来的值与数据库的一致，就不进行加密；反之不加密
                if (!userPwd.equals(user2.getUserpwd())) {
                    // 新密码
                    sysUser.setUserpwd(DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(userTeacherDto.getUserpwd().getBytes()).getBytes()));
                }
            }
            // 用户名
            if (userTeacherDto.getUsername() != null) {
                sysUser.setUsername(userTeacherDto.getUsername());
            }
            // 用户姓名
            if (userTeacherDto.getUsertruename() != null) {
                sysUser.setUsertruename(userTeacherDto.getUsertruename());
            }
            // 用户职业
            if (userTeacherDto.getUseroccupation() != null) {
                sysUser.setUseroccupation(userTeacherDto.getUseroccupation());
            }
            // 专业
            if (userTeacherDto.getUsermajor() != null) {
                sysUser.setUsermajor(userTeacherDto.getUsermajor());
            }
            // 易启学账户id
            if (userTeacherDto.getEdusohoid() != null) {
                sysUser.setEdusohoid(userTeacherDto.getEdusohoid());
            }
            if (userTeacherDto.getUserphone() != null) {
                sysUser.setUserphone(userTeacherDto.getUserphone());
            }
            if (userTeacherDto.getUseremail() != null) {
                sysUser.setUserphone(userTeacherDto.getUseremail());
            }
            if (userTeacherDto.getShowpic() != null) {
                sysUser.setShowpic(userTeacherDto.getShowpic());
            }
            int userUpdate = uMapper.updateById(sysUser); // userUpdate 根据用户id 修改用户时的返回值
            if (userUpdate == 0) {
                throw new Exception("修改用户信息失败！");
            }
            return tMapper.updateById(userTeacherDto);
        } catch (Exception e) {
            e.printStackTrace();
            // @Transactional和try catch捕获异常会让注解失效
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 0;
        }
    }

    /**
     * 根据用姓名模糊查询 用户信息
     *
     * @param name
     * @return SysUser
     */
    @Override
    public List<SysUser> selectSysUserLikeName(String name) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("userstate", 1);
        // 用户输入为空 查询全部
        if (name != null) {
            // 用户输入不为空 根據其用户名查询
            wrapper.like("usertruename", name);
        }
        wrapper.select("userid", "usertruename", "nickname");
        return uMapper.selectList(wrapper);
    }

    /**
     * 根据条件查询用户列表
     *
     * @param user 查询条件:username,userstate,userphone,isteacher,issaler,unionid,openid
     * @return 用户列表
     */
    @Override
    public List<SysUser> selectUserList(SysUser user) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        if (user != null) {
            if (user.getUsername() != null && !user.getUsername().equals("")) {
                wrapper.eq("username", user.getUsername());
            }
        }
        return uMapper.selectList(wrapper);
    }
}
